<?php

require_once WACT_ROOT . '/db/db.inc.php';
require_once APP_ROOT . 'model/common/date.php';
require_once APP_ROOT.'model/common/site.php';

class EvFilter {
    function doFilter(&$vars){
    	if($vars['published']==1) {
    		//if(isset($vars['status']))
    			$status='Published';
    		//else $status='Published (waiting)';
    	} else if($vars['denied']==1)
    		$status='Denied';
    		else $status='Pending';
    	$vars['status']=$status;
    }
}

class PendingEventFilter {
    function doFilter(&$vars) {
    	$event_date = $vars['event_date'];
        $event_date_ts = strtotime( $event_date );

        $tz =& new MyTimeZone();
        $event_date_ts = $tz->timeGMT($event_date_ts);

        if ($event_date_ts  > -1) {
        	$day = gmdate('d', $event_date_ts);
        	$vars['day_of_month']=$day;
        }


    }
}


class Event {

    function insertEvent(&$data) {
        $site_id = Site::getSiteID();
    	$data->set('site_id',$site_id);
        $Record =& DBC::NewRecord($data);
        $published = $data->get('published');

        $event_id = $Record->insertId('sport_events',
            array('eventtext','title', 'user_id', 'admin_user_id', 'date_submitted', 'date',
            'enddate','type','monthday','weekday','weeknumber','startmonth','endmonth','startyear','endyear',
            'published','premium','site_id'),
            'event_id');
        $data->set('event_id',$event_id);

        if ($published) { // only generate pending events for published events
        	//PendingEvent::deletePendingEvents($event_id);
            PendingEvent::generatePendingEvents($data);
        } else {
        	//PendingEvent::deletePendingEvents($event_id);
        }

        return $event_id;
    }

    function &getRecord($id) {
        return DBC::FindRecord("SELECT E.*, U.*, E.title as event_title
        FROM sport_events E
        left outer join sport_users U on E.user_id = U.user_id
        WHERE E.event_id = ". DBC::makeLiteral($id));
    }

    function updateEvent($id, &$data) {
        $site_id = Site::getSiteID();
        $data->set('site_id',$site_id);
        $Record =& DBC::NewRecord($data);
        $published = $data->get('published');
        $event_id = $id;
        $data->set('event_id',$event_id);

        $Record->update('sport_events',
            array('eventtext','title', 'admin_user_id', 'date',
            'enddate','type','monthday','weekday','weeknumber','startmonth','endmonth','startyear','endyear',
            'published','premium','site_id'),
            "event_id=". DBC::makeLiteral($id));
        if ($published) { // only generate pending events for published events
        	PendingEvent::deletePendingEvents($event_id);
            PendingEvent::generatePendingEvents($data);
        } else {
        	PendingEvent::deletePendingEvents($event_id);
        }

    }

    function &getUserEventsList(&$Pager,$user_id) {
        $site_id = Site::getSiteID();
        $isGlobal = Site::IsGlobal();
    	$query="SELECT E.*  FROM sport_events E ";
    	$query.=" where user_id=".DBC::makeLiteral($user_id)."
        and (E.site_id = ".DBC::makeLiteral($site_id);
        if ($isGlobal) $query.=" or 1=1) ";
    	else $query.=") ";

       	return DBC::NewPagedRecordSet($query,$Pager,new EvFilter);
    }

    function delete($id) {
        DBC::execute("DELETE FROM sport_events WHERE event_id=". DBC::makeLiteral($id));
    }


    function getEventsCount($user_id) {
        $site_id = Site::getSiteID();
        $isGlobal = Site::IsGlobal();
        $sql = "Select count(*) from sport_events
    	where user_id=".DBC::makeLiteral($user_id)."
        and (site_id = ".DBC::makeLiteral($site_id);
        if ($isGlobal) $sql.=" or 1=1) ";
    	else $sql.=") ";
    	return DBC::getOneValue($sql);
    }

    function getPublicURLByID($id) {
    	$url = 'calendar/view.htm?pending_event_id='.$id;
    	if (APP_NAME!='.') $url = '/'.APP_NAME.'/'.$url;
    	else  $url = '/'.$url;
    	return $url;
    	//return '/'.APP_NAME.'/'.'pub.event.php?event_id='.$id;
    }

    function getIDByName($name) {
        $site_id = Site::getSiteID();
     	$rec =& DBC::FindRecord("SELECT event_id
     	from sport_events A where A.eventtext = ".DBC::makeLiteral($name)."
        and A.site_id = ".DBC::makeLiteral($site_id)."");
     	if ($rec) return $rec->get('event_id');
     	else return 0;
    }

    function getPublicURLByName($name) {
     		$id = Event::getIDByName($name);
     		$url = Event::getPublicURLByID($id);
     		return $url;
     }

    function getNewEventsCount() {
        $site_id = Site::getSiteID();
    	return DBC::getOneValue("Select count(*) from sport_events
    	where (published = 0 or published is null) and (denied=0 or denied is null)
        and site_id = ".DBC::makeLiteral($site_id)." ");
    }

    function denyEvent($event_id) {
        $data = new DataSpace();
        $data->set('denied',1);
        $data->set('published',0);
    	$Record =& DBC::NewRecord($data);
        $Record->update('sport_events',
            array('denied', 'published'),
            "event_id=". DBC::makeLiteral($event_id));
        PendingEvent::deletePendingEvents($event_id);
    }

    function publishEvent($event_id) {
        $data = new DataSpace();
        $data->set('denied',0);
        $data->set('published',1);
    	$Record =& DBC::NewRecord($data);
        $Record->update('sport_events',
            array('denied', 'published'),
            "event_id=". DBC::makeLiteral($event_id));
        $data =& Event::getRecord($event_id);
        PendingEvent::deletePendingEvents($event_id);
        PendingEvent::generatePendingEvents($data);
    }

    // get the next new article
    function &getNextNewEvent($current_event_id) {
        $site_id = Site::getSiteID();
        $sql = "select E.* from sport_events E, sport_events E2
        where E.event_id <> E2.event_id
        and E2.event_id = ".DBC::makeLiteral($current_event_id)."
        and E.date_submitted <= E2.date_submitted
        and (E.published = 0  or  E.published is null)
        and E.site_id = ".DBC::makeLiteral($site_id)."
        and E2.site_id = ".DBC::makeLiteral($site_id)."
        order by E.date_submitted desc limit 1";
        return DBC::FindRecord($sql);
    }

    function &getEventsList(&$Pager, &$request, &$responseModel) {
        //restore filter from session

     	Session::loadResponseModel($responseModel,'filter.events');
        $site_id = Site::getSiteID();
        $isGlobal = Site::IsGlobal();
     	$sql = "select E.*, U.*, E.title as event_title
     	from sport_events E
     	left outer join sport_users U on E.user_id = U.user_id
        where 1=1 and E.published=1 ".
        " and (E.site_id = ".DBC::makeLiteral($site_id)." ";
        if ($isGlobal) $sql.=" or 1=1) ";
    	else $sql.=") ";
        $sql.= Event::getEventsFilter($request, $responseModel).
     	" order by ".Event::getEventsOrder($request, $responseModel);
     	//print $sql;
        return DBC::NewPagedRecordSet($sql, $Pager);
     }

     function &getNewEventsList(&$Pager, &$request, &$responseModel) {
        $site_id = Site::getSiteID();
        $sql = "select E.*, U.*, E.title as event_title
     	from sport_events E
     	left outer join sport_users U on E.user_id = U.user_id
        where 1=1 and (E.published=0 or E.published is null)
        and E.site_id = ".DBC::makeLiteral($site_id)." order by E.date_submitted desc ";
     	return DBC::NewPagedRecordSet($sql, $Pager);

      }

      function getEventsFilter(&$request, &$responseModel) {
      	$where = '';
      	$filter_event_id = $responseModel->get('filter_event_id');
        $event_id = $responseModel->get('event_id');
      	if ($filter_event_id)  $where .= ' and E.event_id = '.DBC::makeLiteral($event_id);

        $filter_headline = $responseModel->get('filter_headline');
        $headline = $responseModel->get('event_title');
        if ($filter_headline)  $where .= ' and E.title like '.DBC::makeLiteral('%'.$headline.'%').' ';

        $filter_author = $responseModel->get('filter_author');
        $author = $responseModel->get('author');
        if ($filter_author)  $where .= ' and E.user_id = '.DBC::makeLiteral($author);

        return $where;
      }

      function getEventsOrder(&$request, &$responseModel) {
      	$sortby = 'E.date_submitted desc ';
      	$sortby = $responseModel->get('sort');
      	if ($sortby) return 'E.'.$sortby;
      	else return 'E.date_submitted desc ';
      }

      // to do - event occurance description
      function getEventOccurance(&$data) {
      	$type = $data->get('type');
      	$msg = '';
        switch ($type) {
          case 1:
            $mydate = $data->get('date');
            $str_date = SportDate::DbDate2Str($mydate);
            $msg = $str_date;
            break;
          case 2:
            $startdate = $data->get('date');
            $enddate = $data->get('enddate');
            $str_startdate = SportDate::DbDate2Str($startdate);
            $str_enddate = SportDate::DbDate2Str($enddate);
            $msg = "Everyday from ".$str_startdate." to ".$str_enddate;
            break;
          case 3:
            $startdate = $data->get('date');
            $enddate = $data->get('enddate');
            $str_startdate = SportDate::DbDate2Str($startdate);
            $str_enddate = SportDate::DbDate2Str($enddate);
            $monthday = $data->get('monthday');

            $msg = "Every ".$monthday." day of the month from ".$str_startdate." to ".$str_enddate;
            break;
          case 4:
            $startdate = $data->get('date');
            $enddate = $data->get('enddate');
            $str_startdate = SportDate::DbDate2Str($startdate);
            $str_enddate = SportDate::DbDate2Str($enddate);
            $weekday = $data->get('weekday');
            $weekday_name = SportDate::getWeekDay($weekday);
            $msg = "Every ".$weekday_name." from ".$str_startdate." to ".$str_enddate;
            break;
          case 5:
          	$weeknumber = $data->get('weeknumber');
          	$weeknumber_name = SportDate::getWeekNumber($weeknumber);
            $weekday = $data->get('weekday');
            $weekday_name = SportDate::getWeekDay($weekday);
            $startmonth = $data->get('startmonth');
            $startyear = $data->get('startyear');
            $endmonth = $data->get('endmonth');
            $endyear = $data->get('endyear');
            $msg = "Once per month every ".$weeknumber_name." ".$weekday_name." of the month".
            ""." Starting from ".$startmonth."/".$startyear." to ".$endmonth."/".$endyear;
            break;
        }
      	return $msg;
      }
}

class PendingEvent {

   function &getRecord($id) {
        $ds =& DBC::FindRecord("
        select PE.`date` as event_date, PE.`id` as pending_event_id,
        E.*, U.*, E.title as event_title
        FROM sport_events E
        inner join sport_pendingevent PE
        on PE.event_id =  E.event_id
        left outer join sport_users U on E.user_id = U.user_id
        WHERE PE.`id` = ". DBC::makeLiteral($id));

        $event_date = $ds->get('event_date');
        $event_date_ts = strtotime( $event_date );
        $tz =& new MyTimeZone();
        $event_date_ts = $tz->timeGMT($event_date_ts);

        if ($event_date_ts  > -1) {
        	$day = gmdate('d', $event_date_ts);
        	$ds->set('day_of_month',$day);
        }
        return $ds;

    }

    function insertPendingEvent($event_id, $event_date) {
        $data = new DataSpace();
        $data->set('event_id',$event_id);
        $data->set('date',$event_date);

        $Record =& DBC::NewRecord($data);
        $id = $Record->insertId('sport_pendingevent',
            array('event_id','date'),
            'id');
        //print 'Inserted pending event for '.$event_id.' at '.$event_date.' with id ='.$id.'<br>';
        return $id;
    }

    function deletePendingEvents($id) {
        DBC::execute("DELETE FROM sport_pendingevent WHERE event_id=". DBC::makeLiteral($id));
    }

    function &getPendingEventsForMonth($month, $year) {
    	$site_id = Site::getSiteID();
    	$isGlobal = Site::IsGlobal();
        $sql = "select PE.`date` as event_date, PE.`id` as pending_event_id,
        E.*, U.*, E.title as event_title
     	from sport_events E
     	inner join sport_pendingevent PE
     	on E.event_id = PE.event_id
     	left outer join sport_users U on E.user_id = U.user_id
        where 1=1 and E.published=1
        and (E.site_id =  ".DBC::makeLiteral($site_id)." ";
        if ($isGlobal) $sql.=" or 1=1) ";
    	else $sql.=") ";
        $sql .= " and MONTH(PE.`date`) = ".DBC::makeLiteral($month)."
        and YEAR(PE.`date`) = ".DBC::makeLiteral($year)."
     	order by PE.`date` ";
     	return DBC::NewRecordSet($sql, new PendingEventFilter());

    }

    function &getPendingEventsForDay($day, $month, $year) {
    	$site_id = Site::getSiteID();
    	$isGlobal = Site::IsGlobal();
        $sql = "select PE.`date` as event_date, PE.`id` as pending_event_id,
        E.*, U.*, E.title as event_title
     	from sport_events E
     	inner join sport_pendingevent PE
     	on E.event_id = PE.event_id
     	left outer join sport_users U on E.user_id = U.user_id
        where 1=1 and E.published=1
        and (E.site_id =  ".DBC::makeLiteral($site_id)." ";

        if ($isGlobal) $sql.=" or 1=1) ";
    	else $sql.=") ";
        $sql .= " and MONTH(PE.`date`) = ".DBC::makeLiteral($month)."
        and YEAR(PE.`date`) = ".DBC::makeLiteral($year)."
        and DAY(PE.`date`) = ".DBC::makeLiteral($day)."
     	order by PE.`date` ";
     	return DBC::NewRecordSet($sql, new PendingEventFilter());

    }

    function generatePendingEvents(&$data) {
    	$event_id = $data->get('event_id');
        $type = $data->get('type');
        $tz =& new MyTimeZone();

        $event_desc = Event::getEventOccurance($data);
        //print 'Generating pending events for event id:'.$event_id.':'.$event_desc.'<br>';
        $startdate = $data->get('date');
        $enddate = $data->get('enddate');
        $startTS = strtotime($startdate);
        $endTS = strtotime($enddate);


        $startTS = $tz->timeGMT($startTS);
        $endTS = $tz->timeGMT($endTS);

        $day = gmdate('d',$startTS);
        $month = gmdate('m',$startTS);
        $year = gmdate('Y',$startTS);

        switch ($type) {
          case 1:
            $event_date = $startdate;     // single day event
            $id = PendingEvent::insertPendingEvent($event_id, $event_date);
            break;
          case 2:   // every date in the range
            $TS = $startTS;
            while($TS <= $endTS) {
            	// format the date
            	$event_date = gmdate("Y-m-d", $TS);
                $id = PendingEvent::insertPendingEvent($event_id, $event_date);
            	$day++;
            	$TS = gmmktime(0,0,0, $month, $day, $year);
            	//$TS = $tz->timeLocal($TS);
                $day = gmdate('d',$TS);
        		$month = gmdate('m',$TS);
        		$year = gmdate('Y',$TS);
            }

            break;
          case 3:     // day of month in a range
          	$monthday = $data->get('monthday');
            $TS = $startTS;
            while($TS <= $endTS) {
                $date_info = getdate( $TS );
                $current_monthday  = $date_info['mday'];
                if ( $current_monthday == $monthday)  {
               		// format the date
            		$event_date = gmdate("Y-m-d", $TS);
                	$id = PendingEvent::insertPendingEvent($event_id, $event_date);
                }
            	$day++;
            	$TS = gmmktime(0,0,0, $month, $day, $year);
            	//$TS = $tz->timeLocal($TS);
                $day = gmdate('d',$TS);
        		$month = gmdate('m',$TS);
        		$year = gmdate('Y',$TS);
            }

            break;
          case 4:     // day of week
            $weekday = $data->get('weekday');
            $TS = $startTS;
            while($TS <= $endTS) {
                $date_info = getdate( $TS );
                $current_weekday  = $date_info['wday']+1;
                if ( $current_weekday == $weekday)  {
               		// format the date
            		$event_date = gmdate("Y-m-d", $TS);
                	$id = PendingEvent::insertPendingEvent($event_id, $event_date);
                }
            	$day++;
            	$TS = gmmktime(0,0,0, $month, $day, $year);
            	//$TS = $tz->timeLocal($TS);
                $day = gmdate('d',$TS);
        		$month = gmdate('m',$TS);
        		$year = gmdate('Y',$TS);
            }
            break;
          case 5:  // monthly occurence
            $weekday = $data->get('weekday');
            $weeknumber = $data->get('weeknumber');
            $startmonth = $data->get('startmonth');
            $endmonth = $data->get('endmonth');
            $startyear = $data->get('startyear');
            $endyear = $data->get('endyear');
            $month = $startmonth;
            $year = $startyear;
            $startTS = gmmktime(0,0,0, $month, 1, $year);
            $startTS = $tz->timeLocal($startTS);
            $endTS = gmmktime(0,0,0, $endmonth+1, 1, $endyear);
            $endTS = $tz->timeLocal($endTS);

            if (!$startmonth || !$endmonth || !$startyear || !$endyear) break;


            // loop by months
            $monthTS = $startTS;
            while($monthTS < $endTS) {

            	$TS = $monthTS;
            	$day = 1;
            	$endmonthTS = gmmktime(0,0,0, $month+1, 1, $year);
            	//$endmonthTS = $tz->timeLocal($endmonthTS);
            	$weekday_counter = 0;
                while($TS < $endmonthTS) {  // loop by days within the month
                    $date_info = getdate( $TS );
                	$current_weekday  = $date_info['wday']+1;
                	//print date("Y-m-d", $TS).'current_weekday='.$current_weekday.' weekday = '.$weekday;
                	if ( $current_weekday == $weekday ) {
                		$event_date = gmdate("Y-m-d", $TS);  // store the last occurence of the weekday
                		$weekday_counter++;
                	}
                	// weeknumber=5 - last weekday
                    if ( ($weeknumber != 5) && ($weeknumber ==  $weekday_counter) ) {
                        // format the date
            			$event_date = gmdate("Y-m-d", $TS);
                		$id = PendingEvent::insertPendingEvent($event_id, $event_date);
                		break;
                    }
                	$day++;
            		$TS = gmmktime(0,0,0, $month, $day, $year);
            		//$TS = $tz->timeLocal($TS);
                }
                if ( $weeknumber == 5)   {      // use the last date of the weekday
                	$id = PendingEvent::insertPendingEvent($event_id, $event_date);
                }

                $month++;
            	$monthTS = gmmktime(0,0,0, $month, 1, $year);
            	//$monthTS = $tz->timeLocal($monthTS);
                $month = gmdate('m',$TS);
        		$year = gmdate('Y',$TS);
            }
            break;
        }
    }

}

?>
